#include <iostream>
#include "TcpServer.hpp"
#include "Common.hpp"
#include "Command.hpp"
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << "serverip serverport" << std::endl;
        exit(-1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket create error!" << std::endl;
        exit(SOCKED_ERROR);
    }

    struct sockaddr_in server; // 发送给谁？？ server！！
    memset(&server, 0, sizeof(server));
    // 填充servrip && port
    server.sin_family = AF_INET;
    // server.sin_addr.s_addr = inet_addr(serverip.c_str());
    ::inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
    server.sin_port = htons(serverport);
    int n = ::connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect sockfd error!\n"
                  << std::endl;
        exit(-2);
    }
    // 与服务器交互
    while (true)
    {
        std::cout << "Enter# ";
        std::string line;
        std::getline(std::cin, line);
        write(sockfd, line.c_str(), line.size());
        char outbuf[1024];
        n = read(sockfd, outbuf, sizeof(outbuf) - 1);
        if (n > 0)
        {
            // 成功接收server返回的信息
            outbuf[n] = 0;
            std::cout << outbuf << std::endl;
        }
        else
        {
            break;
        }
    }
    return 0;
}